<template>
	<view class="my-page">
		<view class="my-page" v-if="!isLogin">
			<uni-section title="登录" type="line">
				<view class="example">
					<!-- 基础用法，不包含校验规则 -->
					<uni-forms ref="valiForm" :modelValue="userinfo" :rules="rules">
						<uni-forms-item label="用户名" required name="name">
							<uni-easyinput v-model="userinfo.name" placeholder="请输入用户名" />
						</uni-forms-item>
						<uni-forms-item label="密码" required name="password">
							<uni-easyinput v-model="userinfo.password" placeholder="请输入密码" type="password" />
						</uni-forms-item>
					</uni-forms>
					<view class="btn-box">
						<button type="primary" @click="submit('valiForm')" size="mini">登 录</button>
						<button type="default" @click="regeist" size="mini">注 册</button>
					</view>

				</view>
			</uni-section>
			<!-- #ifdef MP-WEIXIN -->
			<!-- <text @tap="weixinLogin" class="weixin-text">使用微信一键登录</text> -->
			<!-- #endif -->
		</view>
		<view class="my-page" v-else>
			<view class="example comflex">
				<view class="user-info">
					<!-- <image :src="loginUser.headpic" mode="widthFix" class="header-image"></image> -->
					<text class="nick-name">欢迎你，<text
							style="color: darkmagenta;">{{loginUser.nickName}}</text>小朋友</text>
				</view>
				<view class="user-info1">
					<text v-if="!isFix">存钱罐余额：{{loginUser.total?loginUser.total:'0'}} 元</text>
					<uni-number-box :min="0" :max="99999999" v-model="money" v-else />
					<button type="warn" @click="fixMoney" v-if="!isFix" size="mini">修改余额</button>
					<button type="primary" @click="saveMoney" v-else size="mini">确定</button>

				</view>
				<view class="tiaozhan">
					<text>其他功能</text>
					<button type="primary" @click="chuangguan" size="mini" class="weixin-text2">口算竞速图表</button>
				</view>

			</view>

			<button type="warn" @tap="quitLogin" class="weixin-text1">退出登录</button>
		</view>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				money: '',
				isFix: false,
				isLogin: false,
				headpic: '',
				userId: '',
				userinfo: {
					name: '',
					password: ''
				},
				loginUser: {},
				// 校验规则
				rules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '用户名不能为空'
						}]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: '密码不能为空'
						}]
					}
				},
			};
		},

		onShow() {
			let userinfo = uni.getStorageSync('LOGIN')
			if (userinfo) {
				this.isLogin = true
				this.getUserInfo(userinfo)
				// this.loginUser = userinfo
			} else {
				this.isLogin = false
			}
		},
		methods: {
			//修改余额
			fixMoney() {
				this.isFix = true
				this.money = this.loginUser.total
			},
			//保存余额
			saveMoney() {
				console.log(this.loginUser)
				console.log('this.money', this.money)
				let obj = {
					total: this.money,
					id: this.loginUser._id
				}
				uniCloud.callFunction({
					name: 'fix-money',
					data: obj
				}).then(res => {
					this.getUserInfo(this.loginUser)
					this.isFix = false
				})
			},
			moneyChange(e) {
				console.log(e)
				this.money = Number(e)
				console.log(this.money)
			},
			//注册
			regeist() {
				uni.navigateTo({
					url: '../zhuce/zhuce'
				})
			},
			//传统登录
			submit(ref) {
				uni.showLoading({
					title: 'loading',
					mask: true
				})
				this.$refs[ref].validate().then(res => {
					console.log('success', res);
					uniCloud.callFunction({
						name: 'save-user',
						data: Object.assign(this.userinfo, {
							sign: 2
						})
					}).then(res => {
						console.log(res)
						if (res.result.status == 0) {
							uni.showToast({
								title: res.result.msg,
								mask: true,
								icon: 'none'
							})
						} else {
							this.isLogin = true
							this.loginUser = res.result.data[0]
							uni.setStorageSync('LOGIN', this.loginUser)
						}
						uni.hideLoading()
					})
				}).catch(err => {
					uni.hideLoading()
					console.log('err', err);
				})
			},
			//退出登录
			quitLogin() {
				uni.removeStorageSync('LOGIN')
				this.isLogin = false
			},
			//微信一键登录
			weixinLogin() {
				uni.showLoading({
					title: 'loading'
				})
				let _this = this;
				// 登录
				uni.login({
					provider: 'weixin',
					success: res => {
						//提交到数据库
						console.log('code', res.code)
						uniCloud.callFunction({
							name: 'get-key',
							data: {
								code: res.code
							}
						}).then(async res1 => {
							console.log('res-openid'.res1)
							_this.userId = res1.openid;
						})

						uni.getUserInfo({
							provider: 'weixin',
							success: async infoRes => {
								console.log(111, infoRes.userInfo)
								// this.userInfo = infoRes.userInfo;
								this.headpic = infoRes.userInfo.avatarUrl
								uniCloud.callFunction({
									name: 'save-user',
									data: {
										name: _this.userId,
										headpic: this.headpic,
										nickName: infoRes.userInfo
											.nickName,
										sign: 1 //微信登录
									}
								}).then(res => {
									console.log(res.result.data[0])
									this.loginUser = res.result
										.data[0]
									uni.setStorageSync('LOGIN',
										this.loginUser)
									this.isLogin = true
									uni.hideLoading()
								})

							},
						})


						// 微信公共平台获取(APPID、APPSecret)
						// APPID
						/* uniCloud.callFunction({
							name: 'get-key'
						}).then(res0 => {
							console.log('code', res.code)
							console.log('res0', res0)
							let appid = res0.result.data[0].appid
							let secret = res0.result.data[0].secret
							let url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid +
								'&secret=' +
								secret + '&js_code=' + res.code + '&grant_type=authorization_code';
							uni.request({
								url: url, // 请求路径
								success: result => {
									console.log('result', result)
									// 获取Id(唯一的)
									_this.userId = result.data.openid;
									console.log("这是openID:" + _this.userId)
									uni.getUserInfo({
										provider: 'weixin',
									}).then(
										res => {
											// 获取用户所有信息
											console.log(res[1].userInfo);
											this.headpic = res[1].userInfo.avatarUrl
										}
									);
								},
							});
						}) */

					},
				});
			},
			//更新用户信息
			getUserInfo(e) {
				uniCloud.callFunction({
					name: 'get-user-info',
					data: {
						id: e._id
					}
				}).then(res => {
					console.log(res)
					this.loginUser = res.result.data[0]
				})
			},

			//查看口算竞速大数据
			chuangguan() {
				uni.navigateTo({
					url: '/pages/kousuan/kousuan'
				})
			}


		}

	}
</script>

<style lang="scss">
	page {
		height: 100%;
	}

	.my-page {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		height: 100%;
	}

	.example {
		padding: 0 30rpx;
	}

	.weixin-text {
		text-align: center;
		margin-bottom: 30rpx;
		color: #1296db;
		font-size: 26rpx;
	}

	.weixin-text1 {
		text-align: center;
		margin-bottom: 30rpx;
		color: #fff;
		font-size: 26rpx;
	}

	.user-info {
		display: flex;
		flex-direction: row;
		align-items: center;
		margin-top: 30rpx;
	}

	.header-image {
		width: 50rpx;
		height: 50rpx;
		border-radius: 50%;
		overflow: hidden;
		margin-right: 16rpx;
	}

	.nick-name {
		font-size: 28rpx;
		color: darkslateblue;
	}

	.btn-box {
		display: flex;
		flex-direction: row;
		justify-content: space-between;
	}

	.mgt {
		margin-top: 30rpx;
	}

	.comflex {
		display: flex;
		flex-direction: column;

	}

	.user-info1 {
		display: flex;
		flex-direction: row;
		justify-content: space-between !important;
		margin-top: 30rpx;
		align-items: center;

		button {
			margin: 0;
		}
	}

	.tiaozhan {
		display: flex;
		flex-direction: column;
		padding-top: 30rpx;
		border-top: 1px solid #eee;
		margin-top: 30rpx;
	}

	.weixin-text2 {
		margin-top: 20rpx;
	}
</style>
